package com.liu.stockmarket.ui.fund

import androidx.lifecycle.*
import com.liu.stockmarket.model.ResponseResult
import com.liu.stockmarket.model.HoldingStockProfit
import com.liu.stockmarket.repository.database.StockRepository
import com.liu.stockmarket.repository.database.TransactionRecordRepository
import com.liu.stockmarket.repository.database.entity.TransactionRecordEntity
import com.liu.stockmarket.repository.network.EasyMoneyRepository
import com.liu.stockmarket.utils.StockTransactionUtil
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.math.BigDecimal

class FundViewModel(
    private val transactionRecordRepository: TransactionRecordRepository,
    private val stockRepository: StockRepository,
    private val easyMoneyRepository: EasyMoneyRepository
) : ViewModel() {

    private val _result = MutableLiveData<ResponseResult<HoldingStockProfit>>()
    val result: LiveData<ResponseResult<HoldingStockProfit>> = _result

    val allFund = stockRepository.allFund.asLiveData()


    /**
     * @see result
     */
    fun getFundTransaction() {

        viewModelScope.launch(Dispatchers.IO) {
            val value = allFund.value
            _result.postValue(StockTransactionUtil.fund(easyMoneyRepository,transactionRecordRepository, value))
        }

    }


    fun deleteByStockId(stockId: Long) {
        viewModelScope.launch(Dispatchers.IO) {
            stockRepository.deleteStock(stockId)
        }

    }

    fun saveDividends(transactionRecordEntity: TransactionRecordEntity):Boolean {
        viewModelScope.launch {
            transactionRecordRepository.save(transactionRecordEntity)
        }
        return true
    }
    fun save(stockId: Long, holdingPrice: BigDecimal, holdingNumber: BigDecimal) {
        viewModelScope.launch(Dispatchers.IO) {
            stockRepository.modifyHoldingPriceAndNumber(stockId, holdingPrice, holdingNumber)
            _result.postValue(ResponseResult.success())
        }

    }



    class FundViewModelFactory(
        private val transactionRecordRepository: TransactionRecordRepository,
        private val stockRepository: StockRepository,
        private val easyMoneyRepository: EasyMoneyRepository
    ) :
        ViewModelProvider.Factory {
        override fun <T : ViewModel?> create(modelClass: Class<T>): T {
            @Suppress("UNCHECKED_CAST")
            return FundViewModel(
                transactionRecordRepository,
                stockRepository,
                easyMoneyRepository
            ) as T
        }

    }

}